//
//  DGTezTagView.swift
//  Digimon
//
//  Created by Vill on 2023/10/25.
//

import UIKit

private var kSideMargin = 10.0
private var kTagHeight = 25.0
private var kTagVerticalMargin = 10.0
private var kTagHorizontalMargin = 10.0
private var kButtonInsideMargin = 8.0
private var kfont = UIFont.systemFont(ofSize: 14)

@objc protocol DGTezTagViewDelegate: AnyObject {
    
    /**
     *  Tag button click event response method.
     *
     *  @param index button index
     */
    @objc optional func responseOfClickTag(index: NSInteger)
    
    /**
     *  选中的数组
     */
    @objc optional func responseOfClickArr(arr: [String])
    
    /**
     *  选中的数组
     */
     @objc optional func responseOfModelarr(modelArr: [Any])
}

class DGTezTagView: UIView, DGTezTagViewDelegate {
    
    weak var delegate: DGTezTagViewDelegate?
    
    var strArr = [String]()
    var tagModelArr = [COTagsModel]()
    var isTagModel = Bool()
    var selectBtn = UIButton()
    
    
    /********************************************************
     optional - If value is not setting, apply default value.
     ********************************************************/
    /**
    *  (Optional) Left and right side margin. If value is not setting, apply TezTagView value.
    * (可选)左右边距。如果value没有设置，则应用TezTagView value。
    */
    var sideMargin = 0.0
    
    /**
     *  (Optional) Tag item button height. If value is not setting, apply TezTagView value.
     *  (可选)标签项按钮高度。如果value没有设置，则应用TezTagView value。
     */
    var tagHeight = 0.0
    
    /**
     *  (Optional) Vertical margin with tag item buttons. If value is not setting, apply TezTagView value.
     *  (可选)带有标签项按钮的垂直边距。如果value没有设置，则应用TezTagView value。
     */
    var tagVerticalMargin = 0.0
    
    /**
     *  (Optional) Horizontal margin with tag item buttons. If value is not setting, apply TezTagView value.
     *  (可选)带有标签项按钮的水平边距。如果value没有设置，则应用TezTagView value。
     */
    var tagHorizontalMargin = 0.0
    
    /**
     *  (可选)带有标签项按钮的内部边距。如果value没有设置，则应用TezTagView value。
     */
    var tagInsideMargin = 0.0


    /**
     *  (Optional) Title font with tag item buttons. If value is not setting, apply TezTagView value.
     *  (可选)带有标签项按钮的标题字体。如果value没有设置，则应用TezTagView value。
     */
    var font = UIFont.systemFont(ofSize: 14)

    /**
     *  (Optional) Tag button background image. If value is not setting, draw border.
     *  (可选)标签按钮背景图片。如果value未设置，则绘制边框。
     */
    var bgImage : UIImage?

    /**
     *  (Optional) TagView set align center.
     *  对齐方式
     */
    var alignCenter = Bool()
    
    var normalTextColor = UIColor.white

    /**
     *   是否可多选
     */
    var isMultiple = Bool()
    
    lazy var selectMarkArray: NSMutableArray = {
        let arr = NSMutableArray()
        return arr
    }()
    
    lazy var chooseModelArr: NSMutableArray = {
        let arr = NSMutableArray()
        return arr
    }()

    init(frame: CGRect,strArr:[String]) {
        super.init(frame: frame)
        self.delegate = self
        self.strArr = strArr
        initValues()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(frame: CGRect,tagStrings:[COTagsModel],isTagModel:Bool) {
        super.init(frame: frame)
        self.delegate = self
        self.tagModelArr = tagStrings
        self.isTagModel = isTagModel
        var showStr = [String]()
        showStr.removeAll()
        for i in 0..<tagStrings.count {
            let model = tagStrings[i]
            let tagStr = "\(model.tagsName)(\(model.hits))"
            showStr.append(tagStr)
        }
        self.strArr = showStr
        initValues()
    }
    
    func initValues(){
        self.sideMargin = -1
        self.tagHeight = -1
        self.tagVerticalMargin = -1
        self.tagHorizontalMargin = -1
        self.tagInsideMargin = -1
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        if (self.sideMargin == -1){
            self.sideMargin = kSideMargin
        }
        if (self.tagHeight == -1){
            self.tagHeight = kTagHeight
        }
        if (self.tagVerticalMargin == -1){
            self.tagVerticalMargin = kTagVerticalMargin
        }
        if (self.tagHorizontalMargin == -1){
            self.tagHorizontalMargin = kTagHorizontalMargin
        }
        if (self.tagInsideMargin == -1){
            self.tagInsideMargin = kButtonInsideMargin
        }
        let maxWidth = SCREENWIDTH - self.sideMargin*2
        var lineWidth = 0.0
        var line = 0
        var lineview = UIView(frame: CGRectMake(self.sideMargin, 0, self.frame.size.width - self.sideMargin*2, self.tagHeight))
        for i in 0..<self.strArr.count {
            let tagWord = self.strArr[i]
            let width = tagWord.width(withFont: self.font) + self.tagInsideMargin*2
            let tagBtn = UIButton(frame: CGRect(x: lineWidth, y: 0, width: width, height: self.tagHeight))
            tagBtn.setTitle(tagWord, for: .normal)
            tagBtn.setTitleColor(normalTextColor, for: .normal)
            tagBtn.setTitleColor(.white, for: .selected)
            tagBtn.titleLabel?.font = font
            tagBtn.tag = i+70
            if(self.bgImage != nil){
                tagBtn.setBackgroundImage(UIImage.resizeWithStretchImage(self.bgImage!), for: .normal)
            }else{
                tagBtn.layer.cornerRadius = self.tagHeight/2
                tagBtn.layer.borderWidth = 1.2
                tagBtn.layer.borderColor = UIColor.white.cgColor
            }
            if(self.isMultiple){
                tagBtn.addTarget(self, action: #selector(onClickTag), for: .touchUpInside)
                tagBtn.setBackgroundImage(UIImage.resizeWithStretchImage(KImaged("coco_tag_normal")), for: .normal)
                tagBtn.setBackgroundImage(UIImage.resizeWithStretchImage(KImaged("coco_tag_select")), for: .selected)
                tagBtn.layer.cornerRadius = self.tagHeight/2
                tagBtn.layer.borderColor = UIColor.clear.cgColor
            }
            if ((lineWidth + (width + kTagVerticalMargin)) <= maxWidth){
                lineWidth += (width + kTagVerticalMargin)
                lineview.addSubview(tagBtn)
            }else{
                if(self.alignCenter){
                    var frame = lineview.frame
                    frame.size.width = lineWidth - kTagVerticalMargin
                    lineview.frame = frame
                    lineview.center = CGPointMake(self.center.x, lineview.center.y)
                }
                addSubview(lineview)
                lineWidth += (width + kTagVerticalMargin)
                line += 1
                lineWidth = 0
                tagBtn.frame = CGRectMake(lineWidth, 0, width, self.tagHeight)
                lineview = UIView(frame: CGRectMake(self.sideMargin, (self.tagHeight + self.tagHorizontalMargin)*Double(line), self.frame.size.width - self.sideMargin*2, self.tagHeight))
                lineWidth += (width + kTagVerticalMargin)
                lineview.addSubview(tagBtn)
            }
        }
        if(self.alignCenter){
            var frame = lineview.frame
            frame.size.width = lineWidth - kTagVerticalMargin
            lineview.frame = frame
            lineview.center = CGPointMake(self.center.x, lineview.center.y)
        }
        self.addSubview(lineview)
    }
    
    
    
    @objc func onClickTag(sender:UIButton){
        if (self.isMultiple == false){
            if (sender == self.selectBtn){
                return
            }
            for i in 0..<self.strArr.count {
                if (sender.tag == i+70){
                    sender.isSelected = true
                    self.selectBtn = sender
                    continue
                }
                let but = self.viewWithTag(i+70) as! UIButton
                but.isSelected = false
            }
            delegate?.responseOfClickTag!(index: sender.tag)
        }else{
            sender.isSelected = !sender.isSelected
            if (self.isTagModel){
                var model = self.tagModelArr[sender.tag - 70]
                let tagStr = "\(model.tagsName)(\(model.hits + 1))"
                if (sender.isSelected){
                    sender.setTitle(tagStr, for: .normal)
                    model.hits += 1
                    self.chooseModelArr.add(model)
                }else{
                    model.hits -= 1
                    let unselectStr = "\(model.tagsName)(\(model.hits))"
                    sender.setTitle(unselectStr, for: .normal)
                    self.chooseModelArr.remove(model)
                }
                delegate?.responseOfModelarr?(modelArr: self.chooseModelArr as! [COTagsModel])
            }else{
                if (sender.isSelected){
                    self.selectMarkArray.add(sender.titleLabel?.text as Any)
                }else{
                    self.selectMarkArray.remove(sender.titleLabel?.text as Any)
                }
                delegate?.responseOfClickArr?(arr: self.selectMarkArray as! [String])
            }
        }
    }
    
    class func getTotalHeightWithDefaultValuesAndWords(words:[String]) -> CGFloat{
        return DGTezTagView.getTotalHeightWithWords(words: words, sMargin: kSideMargin, vMargin: kTagVerticalMargin, hMargin: kTagHorizontalMargin, tMargin: kTagHorizontalMargin, bMargin: kTagHorizontalMargin, IMargin: kButtonInsideMargin, HMargin: kTagHeight, font: kfont)
    }
    
    class func getTotalHeightWithValuesAndWords(words:[String],sMargin:CGFloat,HMargin:CGFloat,IMargin:CGFloat) -> CGFloat{
        return DGTezTagView.getTotalHeightWithWords(words: words, sMargin: sMargin, vMargin: kTagVerticalMargin, hMargin: kTagHorizontalMargin, tMargin: kTagHorizontalMargin, bMargin: kTagHorizontalMargin, IMargin: IMargin, HMargin: HMargin, font: kfont)
    }
    
    class func getTotalHeightWithWords(words:[String],sMargin:CGFloat,vMargin:CGFloat,hMargin:CGFloat,tMargin:CGFloat,
                                 bMargin:CGFloat,IMargin:CGFloat,HMargin:CGFloat,font:UIFont) -> CGFloat{
        var height = tMargin + bMargin
        let maxWidth = SCREENWIDTH - sMargin*2
        var lineWidth = 0.0
        var line = words.count == 0 ? 0 : 1
        for i in 0..<words.count {
            let rcmdWord = words[i]
            let width = rcmdWord.width(withFont: font) + IMargin * 2
            if (i != 0){
                lineWidth += vMargin
            }
            lineWidth += width
            if(lineWidth > maxWidth){
                line += 1
                lineWidth = 0.0
                if (i != 0){
                    lineWidth += vMargin
                }
                lineWidth += width
            }
        }
        let height1 = CGFloat(line) * HMargin
        let hright2 = CGFloat(line - 2) * vMargin
        height += ((height1 + hright2) - vMargin)
        return height
     }
    
}
